package cn.kduck.module.resource.query;

import cn.kduck.core.dao.definition.BeanDefDepository;
import cn.kduck.core.dao.definition.BeanEntityDef;
import cn.kduck.core.dao.query.QueryCreator;
import cn.kduck.core.dao.query.QuerySupport;
import cn.kduck.core.dao.sqlbuilder.ConditionBuilder.ConditionType;
import cn.kduck.core.dao.sqlbuilder.SelectBuilder;
import cn.kduck.core.service.ParamMap;
import cn.kduck.module.resource.service.ResourceService;
import org.springframework.stereotype.Component;

import java.util.Map;

import static cn.kduck.module.resource.service.ResourceService.CODE_RESOURCE_OPERATE;

/**
 * LiuHG
 */
@Component
public class ResourceOperateQuery implements QueryCreator {

    @Override
    public QuerySupport createQuery(Map<String, Object> paramMap, BeanDefDepository depository) {
        BeanEntityDef resourceDef = depository.getEntityDef(ResourceService.CODE_RESOURCE);
        BeanEntityDef operateDef = depository.getEntityDef(ResourceService.CODE_RESOURCE_OPERATE);

        if(paramMap.containsKey("group")){
            SelectBuilder sqlBuilder = new SelectBuilder(paramMap);
            sqlBuilder.from("r",resourceDef).innerJoinOn("o",operateDef,"resourceId").where()
                    .and("r.resource_group", ConditionType.EQUALS,"group")
                    .and("o.operate_path", ConditionType.EQUALS,"path",true)
                    .and("o.method", ConditionType.EQUALS,"method");
            return sqlBuilder.build();
        }else{
            SelectBuilder sqlBuilder = new SelectBuilder(operateDef,paramMap);
            sqlBuilder.where()
                    .and("operate_path", ConditionType.EQUALS,"path",true)
                    .and("method", ConditionType.EQUALS,"method");
            return sqlBuilder.build();
        }
    }
}
